<?php
namespace Api\Controller;
class CreatePayController extends CommonController {
    private $mch = array();
    public $AllPayData = array();
    // passageway
//    public function __construct($transactionData , $get_data , $payName , $mch_id , $PayChannel_MethodName = ''){
//        $data = array(
//            'transactionData' => $transactionData,
//            'get_data' => $get_data,
//            'payName' => $payName,
//            'mch_id' => $mch_id,
//            'PayChannel_MethodName' => $PayChannel_MethodName,
//        );
//
//        $this->InitPassageway($data);
//    }

    /**
     * 返回支付结果与支付信息
     *
     * @access private
     * @param string $systrade_no 系统订单号
     * @param string $code_url 支付二维码
     * @param string $ordernumber 商户订单号
     * @param string $type 扫码 （ 支付宝 微信 QQ ）
     * @return string json
     */
    private function PayResultReturn($systrade_no , $code_url , $ordernumber , $type){
        switch ($type){
            case 'alipay_pay':
//                $yasuo = https_request('http://suo.im/api.php?url=' . urlencode($code_url));
                if($this->AllPayData['PayChannel_MethodName'] != 'aibeipay') { // 爱贝支付通道get url过长并且不能压缩的解决方法
                    $alipayPayUrl = $this->alipaydisplayUrl($code_url, $systrade_no, true);
                }else{
                    $alipayPayUrl = $code_url;
                }
                $success_result = array(
                    'error' => 0,
                    //  'code_img_url' => CreatePayController::qrcode($alipayPayUrl),
                    'ordernumber' => $ordernumber,
                    'payurl' => $alipayPayUrl,
                    'msg' => '创建支付宝订单成功'
                );
                break;
            case 'WeixinScancode':
                $success_result = array(
                    'error' => 0,
                    'code_url' => $code_url,
                     'code_img_url' => CreatePayController::qrcode($code_url),
//                    'weburl' => $this->alipaydisplayUrl($code_url,$systrade_no, false),
                    'ordernumber' => $ordernumber,
                    'msg' => '创建微信扫码支付订单成功'
                );
                break;
            case 'qq_pay':
                $success_result = array(
                    'error' => 0,
                    'payurl' => $code_url,
                    'code_img_url' => CreatePayController::qrcode($code_url),
                    'ordernumber' => $ordernumber,
                    'msg' => '获取手Q窗口支付成功'
                );
                break;
            case 'jd_pay':
                $success_result = array(
                    'error' => 0,
                    'payurl' => $code_url,
                    'ordernumber' => $ordernumber,
                    'msg' => '京东钱包付款订单创建成功'
                );
                break;
            default:
                exit("选择支付类型出错");
        }
        echo json_encode($success_result, JSON_UNESCAPED_UNICODE);
    }

    /* 初始化支付通道并分配通道商户号 */
    public function InitPassageway($data = array()){
        $this->mch = CreatePayController::LoadMchid($data['payName'] , $data['transactionData']['systrade_no'] , $data['mch_id'] , $data['PayChannel_MethodName']);
//        dump($this->mch);die;

//        if($data['PayChannel_MethodName'] == "WeifutongGzhpay"){
//            // 启用轮训机制
//            CreatePayController::WeifutongLunxun(9000 , 100000 , 1000 , 4000);
//        }

        $this->transactionData = $data['transactionData']; // 方便有需要的方法使用
        $this->AllPayData = $data;
        $this->$data['PayChannel_MethodName']($data['get_data']);
        unset($data);
    }

    /*
     * 参数1 商户渠道名
     * 参数2 使用本次分配商户号的系统订单号,用于更新订单使用的商户号与商户通道
     * 参数3 是否指定商户号，如果为空则默认分配
     * */
    private static function LoadMchid($PayChannel, $systrade_no ,$mch_id = '' , $mch_type){
        // 加载支付渠道商户号
        $where = array(
            'pay_type' => $PayChannel ,
            'status' => 0,
        );
        if($mch_id != '') $where['mch_id'] = $mch_id; // 指定商户号
        $mch_config = M("mch_data")->field('mch_id,appid,mch_key,pay_id')->where($where)->find();
        if(empty($mch_config)){
            exit(json_encode(array('error' => 6 , 'msg' => '当前渠道暂无商户号'),JSON_UNESCAPED_UNICODE));
        }
        CreatePayController::updateMchConf($systrade_no , $mch_config['mch_id']  , $mch_type); // 吧分配的商户号更新到订单表中
        return $mch_config;
    }

    /*
     * 更新渠道选择的商户号
     * 参数1 系统生成的流水号
     * 参数2 商户号
     * 参数3 商户渠道
     * no return
     * */

    private static function updateMchConf($sys_order , $mch_id , $mch_type){
        $Model = M("Transaction");
        $Save = array(
            'mch_id' => $mch_id,
            'mch_type' => $mch_type
        );
        $res = $Model->where(array('systrade_no' => $sys_order))->save($Save);
    }


    private static function qrcode($url){
        Vendor('phpqrcode.phpqrcode');
        $level = 'L';
        $size = 6;
        $file_Imgname = "./Public/WeixinCode/" . randNumber('WeixinCode') . '.png';
        \QRcode::png($url, $file_Imgname, $level, $size);
        return S_URL . ltrim($file_Imgname , '.');
    }

    /* 官方支付宝即时到账交易 */
    public function AlipayPay($get_data){
        $payobj = new \Com\Pay\AlipayPay($this->mch);
        $result = $payobj->alipayPay($get_data);
        $success_result = array(
            'error' => 0,
            'order_number' => $get_data['ordernumber'],
            'payurl' => $result,
            'msg' => '创建支付宝订单成功'
        );
        echo json_encode($success_result);
    }

    /* 犇付网银（只支持借记卡） */
    public function BenfuPayBank($get_data){
        $payobj = new \Com\Pay\benfuBankPay($this->mch);
        $bank = array(
            'CMB' => 'CMBCHINA_NET_B2C',
            'CCB' => 'CCB_NET_B2C',
            'BOC' => 'BOC_NET_B2C',
            'ABC' => 'ABC_NET_B2B',
            'BOCM' => 'BOCO_NET_B2B',
            'SPDB' => 'SPDB_NET_B2B',
            'CGB' => 'CGB_NET_B2C',
            'CITIC' => 'ECITIC_NET_B2B',
            'CEB' => 'CEB_NET_B2B',
            'CIB' => 'CIB_NET_B2B',
            'CMBC' => 'CMBC_NET_B2B',
            'HXB' => 'HXB_NET_B2B',
            'BCCB' => 'BCCB_NET_B2B',
            'SHBANK' => 'SHB_NET_B2B',
        );
        $get_data['defaultbank'] = $bank[$this->transactionData['BankType']];
        $transactionRes = $payobj->getUrl($get_data);
        if($transactionRes == '') {
            exit(json_encode(array('error' => 5 , 'msg' => '支付订单发起失败，未知错误'), JSON_UNESCAPED_UNICODE));
        }else{
            echo $transactionRes;
        }
    }

    /* 微付支付RSA-S验签方式支付 */
    public function WeifuPay($get_data){
        $payobj = new \Com\Pay\WeifuPay($this->mch);
        $pay_type = array('WeixinScancode' => 'weixin_scan' , 'alipay_pay' => 'alipay_scan' ,'qq_pay' => 'tenpay_scan' , 'weixinGzh_pay' => 'weixin_h5api');
        $get_data['service_type'] = $pay_type[$get_data['banktype']];
        $transactionRes = $payobj->getUrl($get_data);
        if($transactionRes != '') {
            // 订单创建成功
            $this->PayResultReturn($get_data['systrade_no'] , $transactionRes , $get_data['ordernumber'] , $get_data['banktype']);
        }else{
            echo json_encode(array('error' => 5 , 'msg' => '渠道商导致的支付订单发起失败，未知错误'), JSON_UNESCAPED_UNICODE);
        }
    }


    // 微付 微信H5
    public function WeifuPayH5($get_data){
        $payobj = new \Com\Pay\WeifuPayH5($this->mch);
        $pay_type = array('weixinGzh_pay' => 'weixin_h5api');
        $get_data['service_type'] = $pay_type[$get_data['banktype']];
        $transactionRes = $payobj->getUrl($get_data);
        if($transactionRes != '') {
            // 订单创建成功
            $this->PayResultReturn($get_data['systrade_no'] , $transactionRes , $get_data['ordernumber'] , $get_data['banktype']);
        }else{
            echo json_encode(array('error' => 5 , 'msg' => '渠道商导致的支付订单发起失败，未知错误'), JSON_UNESCAPED_UNICODE);
        }
    }


    /* 趣讯支付宝 微信 支付 */
    public function QuxunPay($get_data){
        $payobj = new \Com\Pay\QuxunPay($this->mch);
        $pay_type = array('alipay_pay' => "1" , 'weixinGzh_pay' => "2");
        $get_data['channel'] = $pay_type[$get_data['banktype']];
        $transactionRes = $payobj->getUrl($get_data);
        if($transactionRes != '') {
            // 订单创建成功
            if($get_data['banktype'] == "weixinGzh_pay"){
                header("Location: " . $transactionRes);
                exit;
            }
            $this->PayResultReturn($get_data['systrade_no'] , $transactionRes , $get_data['ordernumber'] , $get_data['banktype']);
        }else{
            echo json_encode(array('error' => 5 , 'msg' => '渠道商导致的支付订单发起失败，未知错误'), JSON_UNESCAPED_UNICODE);
        }
    }

    /* 讯达支付 */
    public function XunDaPay($get_data){
        $payobj = new \Com\Pay\XunDaPay($this->mch);
        $pay_type = array('bank_pay' => "yt_ylgateway");
        $get_data['orderCode'] = $pay_type[$get_data['banktype']];
        $transactionRes = $payobj->BalanceQuery($get_data);
        if($transactionRes != '') {
            // 订单创建成功
            header("Location: " . $transactionRes);
        }else{
            echo json_encode(array('error' => 5 , 'msg' => '渠道商导致的支付订单发起失败，未知错误'), JSON_UNESCAPED_UNICODE);
        }
    }

    /* ryf讯达支付 */
    public function ryfXunDaPay($get_data){
        $payobj = new \Com\Pay\RyfXunda($this->mch);
        $pay_type = array('jd_pay' => 1);
        $get_data['payType'] = $pay_type[$get_data['banktype']];
        $transactionRes = $payobj->getUrl($get_data);
        if($transactionRes != '') {
            // 订单创建成功
            $this->PayResultReturn($get_data['systrade_no'] , $transactionRes , $get_data['ordernumber'] , $get_data['banktype']);
        }else{
            echo json_encode(array('error' => 5 , 'msg' => '渠道商导致的支付订单发起失败，未知错误'), JSON_UNESCAPED_UNICODE);
        }
    }

    /* 直付通 */
    public function ZhifutongPay($get_data){
        $payobj = new \Com\Pay\ZhifutongPay($this->mch);
        $pay_type = array('weixinGzh_pay' => "h5pay" , 'alipay_pay' => 'alipay' , 'qq_pay' => 'qqpay', 'jd_pay' => 'jdpay');
        $get_data['payType'] = $pay_type[$get_data['banktype']];
        $transactionRes = $payobj->getUrl($get_data);
        if($transactionRes != '') {
            // 订单创建成功
            if($get_data['banktype'] == 'weixinGzh_pay') {
                header("Location: " . $transactionRes);
                exit;
            }

            $this->PayResultReturn($get_data['systrade_no'] , $transactionRes , $get_data['ordernumber'] , $get_data['banktype']);
        }else{
            echo json_encode(array('error' => 5 , 'msg' => '渠道商导致的支付订单发起失败，未知错误'), JSON_UNESCAPED_UNICODE);
        }
    }


    public function WeiPaiPay($get_data){
        $payobj = new \Com\Pay\WeiPaiPay($this->mch);
        $pay_type = array('weixinGzh_pay' => array('url' => 'wxh5/wx_api.do' , 'type' => 'wxpay') ,  'qq_pay' => array('url' => 'qq/qq_api.do' , 'type' => 'qqpay'));
        $get_data['payType'] = $pay_type[$get_data['banktype']];
        $transactionRes = $payobj->getUrl($get_data);
        if($transactionRes != '') {
            // 订单创建成功
            if($get_data['banktype'] == 'weixinGzh_pay'){
                header("Location:" . $this->alipaydisplayUrl($transactionRes , $get_data['ordernumber'] , true));
                exit;
            }
            $this->PayResultReturn($get_data['systrade_no'] , $transactionRes , $get_data['ordernumber'] , $get_data['banktype']);
        }else{
            echo json_encode(array('error' => 5 , 'msg' => '渠道商导致的支付订单发起失败，未知错误'), JSON_UNESCAPED_UNICODE);
        }
    }

    /* 越腾支付 */
    public function YuetengPay($get_data){
        $payobj = new \Com\Pay\YueTengPay($this->mch);
        $pay_type = array('WeixinScancode' => 'wxqr' , 'weixinGzh_pay' => 'wxpublic' , 'alipay_pay' => 'aliqr');
        $get_data['pay_type'] = $pay_type[$get_data['banktype']];
        $transactionRes = $payobj->getUrl($get_data);
        if($transactionRes != '') {
            // 订单创建成功
            $urls = "https://pay.new314.com/pay?token_id=" . $transactionRes;
            if($get_data['banktype'] == 'weixinGzh_pay') {
                header("Location: " .$urls);
                exit;
            }

            if($get_data['banktype'] == 'alipay_pay') {
                $success_result = array(
                    'error' => 0,
                    'payurl' => $urls,
                    'msg' => '创建支付宝订单成功'
                );
            }elseif($get_data['banktype'] == 'WeixinScancode'){
                $success_result = array(
                    'error' => 0,
                    'weburl' => $urls,
                    'ordernumber' => $get_data['ordernumber'],
                    'msg' => '创建微信扫码支付订单成功'
                );
            }

            echo json_encode($success_result, JSON_UNESCAPED_UNICODE);
        }else{
            echo json_encode(array('error' => 5 , 'msg' => '渠道商导致的支付订单发起失败，未知错误'), JSON_UNESCAPED_UNICODE);
        }
    }

    /* 易码通公众号 */
    public function YimaTong($get_data){
        $payobj = new \Com\Pay\YiMatong($this->mch);
        $transactionRes = $payobj->getUrl($get_data);
        if($transactionRes != '') {
            // 订单创建成功
            header("Location: " . $transactionRes);
        }else{
            echo json_encode(array('error' => 5 , 'msg' => '渠道商导致的支付订单发起失败，未知错误'), JSON_UNESCAPED_UNICODE);
        }
    }

    /* 犇付支付宝支付 */
    public function BenfuAlipayPay($get_data){
        $payobj = new \Com\Pay\benFuAlipayPay($this->mch);
        $transactionRes = $payobj->getUrl($get_data);
        if($transactionRes != '') {
            // 订单创建成功
            $success_result = array(
                'error' => 0,
                'payurl' => $this->alipaydisplayUrl($transactionRes,$this->AllPayData['transactionData']['systrade_no']),
                'msg' => '创建支付宝订单成功'
            );
            echo json_encode($success_result, JSON_UNESCAPED_UNICODE);
        }else{
            echo json_encode(array('error' => 5 , 'msg' => '支付订单发起失败，未知错误'), JSON_UNESCAPED_UNICODE);
        }
    }

    /* 犇付QQ支付*/
    public function benfuqqpay($get_data){
        $payobj = new \Com\Pay\QQBenfuPay($this->mch);
        $transactionRes = $payobj->getUrl($get_data);
        if($transactionRes != '') {
            // 订单创建成功
            $success_result = array(
                'error' => 0,
                'payurl' => $transactionRes,
                'ordernumber' => $get_data['ordernumber'],
                'msg' => '获取手Q窗口支付成功'
            );
            echo json_encode($success_result, JSON_UNESCAPED_UNICODE);
        }else{
            echo json_encode(array('error' => 5 , 'msg' => '支付订单发起失败，未知错误'), JSON_UNESCAPED_UNICODE);
        }
    }


    /* 银讯通支付宝支付 */
    public function YinxuntongAlipayPay($get_data){
        $payobj = new \Com\Pay\YinxuntongPayAlipay($this->mch);
        $transactionRes = $payobj->getUrl($get_data);
//        var_dump($transactionRes);die;
        if($transactionRes != '') {
            // 订单创建成功
            $success_result = array(
                'error' => 0,
                'ordernumber' => $get_data['ordernumber'],
                'payurl' => $this->alipaydisplayUrl($transactionRes,$this->AllPayData['transactionData']['systrade_no']),
                'msg' => '创建支付宝订单成功'
            );
            echo json_encode($success_result, JSON_UNESCAPED_UNICODE);
        }else{
            echo json_encode(array('error' => 5 , 'msg' => '支付订单发起失败，未知错误'), JSON_UNESCAPED_UNICODE);
        }
    }

    /* 银讯通银行支付 */
    public function YinxuntongPayBank($get_data){
        $payobj = new \Com\Pay\YinxuntongPayBank($this->mch);
        $bank = array(
            'CCB' => '1004',
            'ABC' => '1002',
            'ICBC' => '1001',
            'BOC' => '1003',
            'SPDB' => '1014',
            'CEB' => '1008',
            'CMB' => '1012',
            'PAYH' => '1011',
            'CIB' => '1013',
            'POST' => '1006',
            'ECITIC' => '1007',
            'HXB' => '1009',
            'CMBCHINA' => '1012',
            'CGB' => '1017',
            'BCCB' => '1016',
            'SHB' => '1025',
            'CMBC' => '1010',
            'BOCM' => '1005',
            'BJRCB' => '1103',
        );
        $get_data['defaultbank'] = $bank[$this->transactionData['BankType']];
        $transactionRes = $payobj->getUrl($get_data);
        if($transactionRes == '') {
            exit(json_encode(array('error' => 5 , 'msg' => '支付订单发起失败，未知错误'), JSON_UNESCAPED_UNICODE));
        }else{
            header("Location:" . $transactionRes);
        }
    }


    /* 银讯通微信扫码支付*/
    public function YinxuntongSMpay($get_data){
//        $payName = 'YinxuntongGZh'; // YinxuntongGZh //测试完之后记得换成正式商户号!!
        $payobj = new \Com\Pay\YinxuntongSMPay($this->mch);
        $transactionRes = $payobj->getUrl($get_data);
        if($transactionRes['qrcode'] != '') {
            // 订单创建成功
            $success_result = array(
                'error' => 0,
                'code_img_url' => CreatePayController::qrcode($transactionRes['qrcode']),
                'code_url' => $transactionRes['qrcode'],
                'ordernumber' => $get_data['ordernumber'],
                'msg' => '创建微信扫码支付订单成功'
            );
            echo json_encode($success_result, JSON_UNESCAPED_UNICODE);
        }else{
            echo json_encode(array('error' => 5 , 'msg' => '支付订单发起失败，未知错误'), JSON_UNESCAPED_UNICODE);
        }
    }

    /* QQ支付*/
    public function Yinxuntongqqpay($get_data){
//        $payName = 'YinxuntongGZh'; // YinxuntongGZh //测试完之后记得换成正式商户号
        $payobj = new \Com\Pay\QqPay($this->mch);
        $transactionRes = $payobj->getUrl($get_data);
        if($transactionRes != '') {
            // 订单创建成功
            $success_result = array(
                'error' => 0,
                'payurl' => $transactionRes,
                'ordernumber' => $get_data['ordernumber'],
                'msg' => '获取手Q窗口支付成功'
            );
            echo json_encode($success_result, JSON_UNESCAPED_UNICODE);
        }else{
            echo json_encode(array('error' => 5 , 'msg' => '支付订单发起失败，未知错误'), JSON_UNESCAPED_UNICODE);
        }
    }


    /* 欧创公众号支付*/
    public function ouchuangGzh($transactionData , $get_data , $payName , $mch_id){
//        $payName = 'ouchuang';
        $mch = CreatePayController::LoadMchid($payName , $transactionData['systrade_no'] , $mch_id , $this->getactionname(__METHOD__));
        $payobj = new \Com\Pay\OuchuangGzhPay($mch);
        $transactionRes = $payobj->getUrl($get_data);
        if($transactionRes != '') {
            // 订单创建成功
           header("Location:" . $transactionRes);  // 直接跳转到支付地址掉起支付
//            echo json_encode($success_result, JSON_UNESCAPED_UNICODE);
        }else{
            echo json_encode(array('error' => 5 , 'msg' => '支付订单发起失败，未知错误'), JSON_UNESCAPED_UNICODE);
        }
    }


    /* 犇付公众号支付支付 */
    public function BenfuGzh($get_data){
//        $payName = 'benfuGzh';
        $openid = $this->CheckOpenid($this->mch['pay_id'], $this->AllPayData['transactionData']['merchant'], $this->AllPayData['transactionData']['user_id'], $this->AllPayData['transactionData']['systrade_no'], $this->AllPayData['PayChannel_MethodName'], $this->AllPayData['payName'], $this->mch['mch_id']);
        $get_data['openid'] = $openid;
        $pay_obj = new \Com\Pay\benFuGzhPay($this->mch);
        $getUrl = $pay_obj->getUrl($get_data);
        if ($getUrl != '') {
            $this->transferH5Pay($getUrl , $get_data['return_url'] , 'Benfu');
        } else {
            echo "<script>alert('系统繁忙...');javascript:history.go(-1);</script>";
            return;
        }
    }


    /* 通联公众号支付*/
    public function TonglianGzh($transactionData , $get_data , $payName , $mch_id){
//        $payName = 'tonglian';
        $actionName = $this->getactionname(__METHOD__);
        $mch = CreatePayController::LoadMchid($payName , $transactionData['systrade_no'] , $mch_id , $actionName);
        $openid = $this->CheckOpenid($mch['pay_id'] , $transactionData['merchant'] , $transactionData['user_id'] , $transactionData['systrade_no'] , $actionName , $payName , $mch_id);
        $get_data['openid'] = $openid;
        $payobj = new \Com\Pay\TonglianPay($mch);
        $transactionRes = $payobj->getUrl($get_data);
        if($transactionRes != '') {
            // 订单创建成功
            $this->transferH5Pay($transactionRes , $get_data['return_url'] , 'Tonglian');

        }else{
            echo json_encode(array('error' => 5 , 'msg' => '支付订单发起失败，未知错误'), JSON_UNESCAPED_UNICODE);
        }
    }

    /* 通联公众号支付*/
    public function XpayGzh($transactionData , $get_data , $payName , $mch_id){
//        $payName = 'Xpay';
        $actionName = $this->getactionname(__METHOD__);
        $mch = CreatePayController::LoadMchid($payName , $transactionData['systrade_no'] , $mch_id , $actionName);
        $openid = $this->CheckOpenid($mch['pay_id'] , $transactionData['merchant'] , $transactionData['user_id'] , $transactionData['systrade_no'] , $actionName , $payName , $mch_id);
        $get_data['openid'] = $openid;
        $payobj = new \Com\Pay\XGzhPay($mch);
        $transactionRes = $payobj->getUrl($get_data);
        if($transactionRes != '') {
            $transactionRes['package'] = $transactionRes['pack'];
            // 订单创建成功
            $this->transferH5Pay($transactionRes , $get_data['return_url'] , 'Tonglian');
        }else{
            echo json_encode(array('error' => 5 , 'msg' => '支付订单发起失败，未知错误'), JSON_UNESCAPED_UNICODE);
        }
    }


    /* 畅捷公众号支付*/
    public function ChangjieGzh($get_data){
//        $payName = 'Changjie';
        $openid = $this->CheckOpenid($this->mch['pay_id'], $this->AllPayData['transactionData']['merchant'], $this->AllPayData['transactionData']['user_id'], $this->AllPayData['transactionData']['systrade_no'], $this->AllPayData['PayChannel_MethodName'], $this->AllPayData['payName'], $this->mch['mch_id']);
        $get_data['openid'] = $openid;
        $payobj = new \Com\Pay\ChangJiePay($this->mch);
        $transactionRes = $payobj->getUrl($get_data);
        if($transactionRes != '') {
            $this->transferH5Pay($transactionRes , $get_data['return_url'] , 'Chanjie');
        }else{
            echo json_encode(array('error' => 5 , 'msg' => '支付订单发起失败，未知错误'), JSON_UNESCAPED_UNICODE);
        }
    }


    /* 浦发银行*/
    public function PufaPay($get_data){
        // 52924603   红创世纪公众号  32
        // 54172561   星宏星付公众号  47
        // 54188813   福兴利电脑公众号 28
        // 54200159   金度商城公众号  30

        # 选择不同的支付类型传值
        if($get_data['banktype'] == 'weixinGzh_pay') { // 第一次获取openid的时候，第一条表达式不会成立
            $openid = $this->CheckOpenid($this->mch['pay_id'], $this->AllPayData['transactionData']['merchant'], $this->AllPayData['transactionData']['user_id'], $this->AllPayData['transactionData']['systrade_no'], $this->AllPayData['PayChannel_MethodName'], $this->AllPayData['payName'], $this->mch['mch_id']);
            $get_data['openid'] = $openid;
            $get_data['productId'] = '0112';
            $get_data['transId'] = '16';
            $get_data['subOpenId'] = $openid;
        }elseif($get_data['banktype'] == 'WeixinScancode'){
            $get_data['productId'] = '0108';
            $get_data['transId'] = '10';
        }elseif($get_data['banktype'] == 'alipay_pay'){
            $get_data['productId'] = '0119';
            $get_data['transId'] = '10';
        }

        $payobj = new \Com\Pay\PFPay($this->mch);
        $transactionRes = $payobj->getAlisubMchid($get_data);
        if($transactionRes != '') {
            if($get_data['banktype'] == 'weixinGzh_pay'){
//                $this->transferH5Pay(json_decode($transactionRes['formfield'], true), $get_data['return_url'], 'Pufa');
                header("Location: " . $transactionRes);
                exit;
            }
            $this->PayResultReturn($get_data['systrade_no'] , $transactionRes , $get_data['ordernumber'] , $get_data['banktype']);
        }else{
            echo json_encode(array('error' => 5 , 'msg' => '支付订单发起失败，未知错误'), JSON_UNESCAPED_UNICODE);
        }
    }



    /* 易票联公众号（扫码）支付*/
    public function Yipiaolian($get_data){
        $payobj = new \Com\Pay\YipiaolianPay($this->mch);
        $pay_type = array('WeixinScancode' => 'wxNative' , 'alipay_pay' => 'alipayQrCode');
        $get_data['pay_id'] = $pay_type[$get_data['banktype']];
        $transactionRes = $payobj->getUrl($get_data);
        if(!empty($transactionRes)) {
            $this->PayResultReturn($get_data['systrade_no'] , $transactionRes , $get_data['ordernumber'] , $get_data['banktype']);
        }else{
            echo json_encode(array('error' => 5 , 'msg' => '支付订单发起失败，未知错误'), JSON_UNESCAPED_UNICODE);
        }
    }



//    public function weixin_pay(){
//        $md5Key = 'admin1234567';
//        $type = I('get.type');
//        if($type == 'create') {
//            $sign = I('get.sign');
//            $transactionData = I('get.transactionData');
//            $MySign = md5($transactionData . $type . '7344db8f3618037b70217a002bcbbd2e');
//            if ($sign != $MySign) exit('sign error');
//            $transactionData  = $params = json_decode(\Think\Crypt\Driver\Think::decrypt($transactionData , '#Changbao20170725#'),true);
////            dump($transactionData);die;
//        }elseif($type == 'getopenid_after'){
////            I('')
//            $params = I('get.params');
//            $sign = I('get.sign');
//            $type = I('get.type');
//
//            $MySign = strtoupper(md5($params  . $type . $md5Key));
//            if($MySign != $sign) exit("sign error");
//            $transactionData = json_decode(\Think\Crypt\Driver\Think::decrypt($params, '#Changbao20170725#'),true);
//        }
//
//        $mch = $this->LoadMchid('WeifutongGzh');
//        if(empty($mch)){
//            exit(json_encode(array('error' => 6 , 'msg' => '当前渠道暂无商户号'),JSON_UNESCAPED_UNICODE));
//        }
//
//        $openid = M('user_extend')->where(array('pay_id' => $mch['pay_id'] ,  'mch_id' => $transactionData['merchant'] , 'user_id' => $transactionData['user_id']))->getField('wx_recharge_openid');
//        if(empty($openid)) {
////            $params = \Think\Crypt\Driver\Think::encrypt(json_encode($transactionData), '#Changbao20170725#');
//            $key = strtoupper(md5($params  . 'getopenid_after' . $md5Key));
//            $return_url = S_URL . '/Api/CreatePay/weixin_pay?type=getopenid_after&params=' . $params . '&sign=' . $key;
//            A("Openid")->getPayOpenid($mch['pay_id'], $transactionData['user_id'], $transactionData['merchant'], $return_url);
//        }else{
//            $this->WeifutongGzhpay($transactionData , $openid , $mch);
//        }
//
//    }

    /**
     * 检查openid是否获取 , 有直接返回没有跳转获取
     *
     * @access private
     * @param int $pay_id 商户号所属pay_id
     * @param int $merchant 回传商户号
     * @param int $user_id 用户id
     * @param string $user_id 支付请求的系统订单号
     * @param string $method_name 记录调用本方法的方法名，用于回调跳转
     * @return string Wx openid
     */

    private function CheckOpenid($pay_id , $merchant , $user_id , $systrade_no , $method_name , $payName , $mch_id){
        $openid = M('user_extend')->where(array('pay_id' => $pay_id ,  'mch_id' => $merchant , 'user_id' => $user_id))->getField('wx_recharge_openid');
        if($openid == '') {
            $Sign = strtoupper(md5($systrade_no . $method_name. $payName . $mch_id. $user_id . C("SignKey")));
            $return_url = S_URL . '/Api/CreatePay/setOpenidCallback?order=' . base64_encode($systrade_no)  . '&clbkname=' . base64_encode($method_name) .'&payName=' . $payName .'&mch_id='. $mch_id . '&user_id=' . $user_id . '&sign=' . $Sign;
            A("Openid")->getPayOpenid($pay_id, $user_id, $merchant, $return_url);
            exit;
        }
        return $openid;
    }


    public function setOpenidCallback(){
        if(I('get.order') != ''){
            $MethodName = base64_decode(I('get.clbkname'));
            $user_id = I('get.user_id');
            $payName = I('get.payName');
            $mch_id = I('get.mch_id');
            $order = base64_decode(I('get.order'));
            $mysign = strtoupper(md5($order . $MethodName . $payName . $mch_id . $user_id . C("SignKey")));

            if($mysign != I('get.sign')) exit("sign error");
            $transactionData = M("Transaction")->where(array('systrade_no' => $order))->find();
            $transactionData['user_id'] = $user_id; // 公众号支付加入用户user_id
            // 重新整合支付信息数组再次跳转到公众号支付方法进行支付
                $this->AllPayData = array(
                    'transactionData' => $transactionData,
                    'get_data' => self::getparameter($transactionData),
                    'payName' => $payName,
                    'mch_id' => $mch_id,
                    'PayChannel_MethodName' => $MethodName,
                );
            $this->mch = M("mch_data")->field('mch_id,appid,mch_key,pay_id')->where(array('mch_id' => $mch_id , 'pay_type' => $payName))->find();
            $this->$MethodName($this->AllPayData['get_data']);
        }
    }

    /* 威富通公众号支付 */
    public function WeifutongGzhpay($get_data){
        $openid = $this->CheckOpenid($this->mch['pay_id'], $this->AllPayData['transactionData']['merchant'], $this->AllPayData['transactionData']['user_id'] , $this->AllPayData['transactionData']['systrade_no'], $this->AllPayData['PayChannel_MethodName'], $this->AllPayData['payName'], $this->mch['mch_id']); // openid获取完毕之后需要传入继续支付的方法
        $get_data['openid'] = $openid;
        $payobj = new \Com\Pay\WeiFuTongPay($this->mch);
        $transactionRes = $payobj->getUrl($get_data);
        if($transactionRes != '') {
            // 订单创建成功
//            $url = 'https://pay.swiftpass.cn/pay/jspay?token_id=' . $transactionRes;
//            header("Location: " . $url);
            $this->transferH5Pay(json_decode($transactionRes) , $get_data['return_url'] , 'Weifutong'); // 掉起H5页面进行支付
        }else{
            echo json_encode(array('error' => 5 , 'msg' => '渠道商导致的支付订单发起失败，未知错误'), JSON_UNESCAPED_UNICODE);
        }
    }




    /* 公众号支付 */
    public function HaofuPay($get_data){
        $payobj = new \Com\Pay\HaofuPay($this->mch);
        $transactionRes = $payobj->getUrl($get_data);
        if($transactionRes != '') {
            // 订单创建成功
            header("Location: " . $transactionRes);
        }else{
            echo json_encode(array('error' => 5 , 'msg' => '渠道商导致的支付订单发起失败，未知错误'), JSON_UNESCAPED_UNICODE);
        }
    }


    /* 中亿支付 */
    public function ZhongyiPay($get_data){
        $payobj = new \Com\Pay\zhongyiPay($this->mch);
        $pay_type = array('WeixinScancode' => 'WXPAY' , 'alipay_pay' => 'ZFBPAY');
        $get_data['wxweb'] = $pay_type[$get_data['banktype']];
        $transactionRes = $payobj->getUrl($get_data);
        if($transactionRes != '') {
            $this->PayResultReturn($get_data['systrade_no'] , $transactionRes , $get_data['ordernumber'] , $get_data['banktype']);
        }else{
            echo json_encode(array('error' => 5 , 'msg' => '渠道商导致的支付订单发起失败，未知错误'), JSON_UNESCAPED_UNICODE);
        }
    }

    /* 爱贝支付 */
    public function aibeipay($get_data){
        $payobj = new \Com\Pay\AibeiPay($this->mch);
        $pay_type = array('WeixinScancode' => 'WXPAY' , 'alipay_pay' => 'ZFBPAY');
        $get_data['wxweb'] = $pay_type[$get_data['banktype']];
        $transactionRes = $payobj->getUrl($get_data);
        if($transactionRes != '') {
            $this->PayResultReturn($get_data['systrade_no'] , $transactionRes , $get_data['ordernumber'] , $get_data['banktype']);
        }else{
            echo json_encode(array('error' => 5 , 'msg' => '渠道商导致的支付订单发起失败，未知错误'), JSON_UNESCAPED_UNICODE);
        }
    }


    /* WanYouFu */
    public function WanYouFuPay($get_data){
        $payobj = new \Com\Pay\WanYouFuPay($this->mch);
        $pay_type = array('WeixinScancode' => array('type' => 2 , 'send_url' => 'http://39.108.201.48/Pay/GateWayTencent.aspx') , 'alipay_pay' => array('type' => 2 , 'send_url' => 'http://39.108.201.48/Pay/GateWayAliPay.aspx') , 'qq_pay' => array('type' => 4 , 'send_url' => 'http://39.108.201.48/Pay/GateWayTencent.aspx') , 'weixinGzh_pay' => array('type' => 2 , 'send_url' => 'http://39.108.201.48/Pay/GateWayTencent.aspx'));
        $get_data['pay_type'] = $pay_type[$get_data['banktype']];
        $transactionRes = $payobj->getUrl($get_data);
        if($transactionRes != '') {
            // 订单创建成功
            if($get_data['banktype'] == 'weixinGzh_pay'){
                header("Location:" . $this->alipaydisplayUrl($transactionRes , $get_data['ordernumber'] , true));
                exit;
            }
            $this->PayResultReturn($get_data['systrade_no'] , $transactionRes , $get_data['ordernumber'] , $get_data['banktype']);
        }else{
            echo json_encode(array('error' => 5 , 'msg' => '渠道商导致的支付订单发起失败，未知错误'), JSON_UNESCAPED_UNICODE);
        }
    }

    /* 美联支付 */
    public function meilianPay($get_data){
        $payobj = new \Com\Pay\MeilianPay($this->mch);
//        $pay_type = array('WeixinScancode' => 'WX_SM' , 'alipay_pay' => 'ALI_SM' , 'qq_pay' => 'QQ_SM' , 'weixinGzh_pay' => 'WX_PUBLIC');
        $pay_type = array('WeixinScancode' => 'WX_SM' , 'alipay_pay' => 'ALI_SM' , 'qq_pay' => 'QQ_SM' , 'weixinGzh_pay' => 'WX_H5');
        $get_data['wxweb'] = $pay_type[$get_data['banktype']];
        $transactionRes = $payobj->getUrl($get_data);
        if($transactionRes != '') {
            // 订单创建成功
            if($get_data['banktype'] == 'weixinGzh_pay'){
                header("Location:" . $transactionRes);
                exit;
            }
            $this->PayResultReturn($get_data['systrade_no'] , $transactionRes , $get_data['ordernumber'] , $get_data['banktype']);
        }else{
            echo json_encode(array('error' => 5 , 'msg' => '渠道商导致的支付订单发起失败，未知错误'), JSON_UNESCAPED_UNICODE);
        }
    }

    /* 微信官方公众号支付 */
    public function WeixinGzhPay($get_data){
        $openid = $this->CheckOpenid($this->mch['pay_id'], $this->AllPayData['transactionData']['merchant'], $this->AllPayData['transactionData']['user_id'] , $this->AllPayData['transactionData']['systrade_no'], $this->AllPayData['PayChannel_MethodName'], $this->AllPayData['payName'], $this->mch['mch_id']); // openid获取完毕之后需要传入继续支付的方法
        $get_data['openid'] = $openid;
        $payobj = new \Com\Pay\WeixinGzhPay($this->mch);
        $transactionRes = $payobj->getUrl($get_data);
//        $transactionRes = $payobj->OrderIsPay('4200000008201709264384648568');
        if(is_array($transactionRes)) {
            // 订单创建成功
            $this->transferH5Pay($transactionRes , $get_data['return_url'] , 'WeixinGzhPay'); // 掉起H5页面进行支付
        }else{
            echo json_encode(array('error' => 5 , 'msg' => '渠道商导致的支付订单发起失败，未知错误'), JSON_UNESCAPED_UNICODE);
        }
    }

    /* ↑↑↑↑↑↑↑ */
    public function QuanfutongGzhpay($transactionData , $get_data ,  $payName , $mch_id){
        $actionName = $this->getactionname(__METHOD__); // 保存本方法的方法名
        $mch = CreatePayController::LoadMchid($payName  , $transactionData['systrade_no'], $mch_id , $actionName);
        $openid = $this->CheckOpenid($mch['pay_id'] , $transactionData['merchant'] , $transactionData['user_id'] , $transactionData['systrade_no'] , $actionName, $payName , $mch_id); // openid获取完毕之后需要传入继续支付的方法
        $get_data['openid'] = $openid;
        $payobj = new \Com\Pay\WeiFuTongPay($mch);
        $transactionRes = $payobj->getUrl($get_data);
        if($transactionRes != '') {
            // 订单创建成功
            $url = 'https://pay.swiftpass.cn/pay/jspay?token_id=' . $transactionRes;
            header("Location: " . $url);
        }else{
            echo json_encode(array('error' => 5 , 'msg' => '渠道商导致的支付订单发起失败，未知错误(全付通)'), JSON_UNESCAPED_UNICODE);
        }
    }


    public function ShandeGzhPay($get_data, $openid = array() , $mch = array()){
       if(count($openid) < 2){
           $redirectParams = array(
               'transactionData' => $this->AllPayData['transactionData'],
               'get_data' => $get_data,
               'payName' => $this->AllPayData['payName'],
               'mch' => $this->mch
           );
           $AseParams =  \Think\Crypt\Driver\Think::encrypt(json_encode($redirectParams), C('encryptKey') , 5);
           $this->redirect(S_URL . '/Api/Openid/ShandeGetopenid?Parames=' . $AseParams);
           exit;
       }
        $get_data['openid'] = $openid['open_id'];
        $get_data['sub_open_id'] = $openid['sub_open_id'];
        $payobj = new \Com\Pay\ShandeGzhPay($mch);
        $transactionRes = $payobj->getUrl($get_data);
        if($transactionRes != '') {
            // 订单创建成功
            header("Location: " . $transactionRes);
        }else{
            echo json_encode(array('error' => 5 , 'msg' => '渠道商导致的支付订单发起失败，未知错误'), JSON_UNESCAPED_UNICODE);
        }
    }


    private function getactionname($action){
        return explode('::' , $action)[1];
    }

    /* 威富通扫码支付支付 */
    public function weifutongSMPay($get_data){
//        $payName = "weifutongSM"; // 这个Name是从mch_data中的pay_type里面的拿的
        // 威富通扫码支付现在是使用轮询方法来分配商户号

        $lunxun = true;
        if($lunxun) {
            $mch = CreatePayController::WeifutongLunxun(0.00, 0.00, 10, 20, $this->AllPayData['PayName']);
            if (empty($mch)) {
                exit(json_encode(array('error' => 6, 'msg' => '当前渠道暂无商户号(轮询)'), JSON_UNESCAPED_UNICODE));
            }

            CreatePayController::updateMchConf($this->AllPayData['transactionData']['systrade_no'], $mch['mch_id'], $this->AllPayData['PayName']); // 吧分配的商户号更新到订单表中
        }else{
//            $actionName = $this->getactionname(__METHOD__);
            $mch = CreatePayController::LoadMchid($this->AllPayData['PayName'] , $this->AllPayData['transactionData']['systrade_no'], $this->AllPayData['mch_id'] , $this->AllPayData['PayChannel_MethodName']);
        }

        $WeifutongSM = new \Com\Pay\WeiFuTongSMPay(array('mch_id' => $mch['mch_id'] , 'mch_key' => $mch['mch_key']));
        $res = $WeifutongSM->getUrl($get_data);
        if($res != '') {
            // 订单创建成功
            $success_result = array(
                'error' => 0,
                'code_img_url' => $res['code_img_url'],
                'code_url' => $res['code_url'],
                'ordernumber' => $get_data['ordernumber'],
                'msg' => '创建微信扫码支付订单成功'
            );
            echo json_encode($success_result, JSON_UNESCAPED_UNICODE);
        }else{
            echo json_encode(array('error' => 5 , 'msg' => '渠道商导致的支付订单发起失败，未知错误'), JSON_UNESCAPED_UNICODE);
        }
    }


    /* 犇付扫码支付 */
    public function BenfuSMPay($get_data){
        $obj = new \Com\Pay\benFuSmPay($this->mch);
        $res = $obj->getUrl($get_data);
        if($res != '') {
            // 订单创建成功
            $success_result = array(
                'error' => 0,
                'code_img_url' => CreatePayController::qrcode($res),   // 犇付没有直接二维码图片
                'code_url' => $res,
                'weburl' => $this->alipaydisplayUrl($res,$this->AllPayData['transactionData']['systrade_no'] , true),
                'ordernumber' => $get_data['ordernumber'],
                'msg' => '创建微信扫码支付订单成功(犇付)'
            );
            echo json_encode($success_result, JSON_UNESCAPED_UNICODE);
        }else{
            echo json_encode(array('error' => 5 , 'msg' => '渠道商导致的支付订单发起失败，未知错误'), JSON_UNESCAPED_UNICODE);
        }
    }



    /* 旅易扫码支付 */
    public function LvyiPaySaoma($get_data){
//        $payName = "LvyiPay";
        $get_data['service'] = '0002'; // 此通道需要传动态类型
        $Lvyipay = new \Com\Pay\LvyiPay($this->mch);
        $res = $Lvyipay->getUrl($get_data);
        if($res != '') {
            $this->PayResultReturn($get_data['systrade_no'] , $res['payUrl'] , $get_data['ordernumber'] , $get_data['banktype']);
        }else{
            echo json_encode(array('error' => 5 , 'msg' => '渠道商导致的支付订单发起失败，未知错误'), JSON_UNESCAPED_UNICODE);
        }
    }


    /* ↑↑↑↑↑↑↑↑↑↑ */
    public function XiangyiPaySaoma($get_data){
        $get_data['service'] = '0002'; // 此通道需要传动态类型
        $Lvyipay = new \Com\Pay\LvyiPay($this->mch);
        $res = $Lvyipay->getUrl($get_data);
        if($res != '') {
            $this->PayResultReturn($get_data['systrade_no'] , $res['payUrl'] , $get_data['ordernumber'] , $get_data['banktype']);
        }else{
            echo json_encode(array('error' => 5 , 'msg' => '渠道商导致的支付订单发起失败，未知错误'), JSON_UNESCAPED_UNICODE);
        }
    }


    /* 得成扫码支付 */
    public function DechengSMPay($transactionData , $get_data  , $payName , $mch_id){
//        $payName = "DechengPay";
        $mch = CreatePayController::LoadMchid($payName , $transactionData['systrade_no'] ,$mch_id , $this->getactionname(__METHOD__));
        $DechengObj = new \Com\Pay\DechengSMPay(array('mch_id' => $mch['mch_id'] , 'mch_key' => $mch['mch_key']));
        $res = $DechengObj->getUrl($get_data);
        if($res != '') {
            // 订单创建成功
            $success_result = array(
                'error' => 0,
                'code_url' => $res['qrCodeUrl'],
                'code_img_url' => CreatePayController::qrcode($res['qrCodeUrl']),
                'ordernumber' => $get_data['ordernumber'],
                'msg' => '创建微信扫码支付订单成功'
            );
            echo json_encode($success_result, JSON_UNESCAPED_UNICODE);
        }else{
            echo json_encode(array('error' => 5 , 'msg' => '渠道商导致的支付订单发起失败，未知错误'), JSON_UNESCAPED_UNICODE);
        }
    }


    /* 得成支付宝扫码支付 */
    public function DechengAlipayPay($get_data){
//        $payName = "DechengPay";
        $DechengObj = new \Com\Pay\DechengAlipayPay($this->mch);
        $res = $DechengObj->getUrl($get_data);
        if($res != '') {
            $success_result = array(
                'error' => 0,
                'payurl' => $this->alipaydisplayUrl($res['qrCodeUrl'],$this->AllPayData['transactionData']['systrade_no']),
                'code_img_url' => CreatePayController::qrcode($res['qrCodeUrl']),
                'ordernumber' => $get_data['ordernumber'],
                'msg' => '创建支付宝订单成功'
            );
            echo json_encode($success_result, JSON_UNESCAPED_UNICODE);
        }else{
            echo json_encode(array('error' => 5 , 'msg' => '渠道商导致的支付订单发起失败，未知错误'), JSON_UNESCAPED_UNICODE);
        }
    }

    /* 旅易QQ支付 */
    public function LvyiQQpay($transactionData , $get_data , $payName , $mch_id){
//        $payName = "LvyiPay";
        $mch = CreatePayController::LoadMchid($payName , $transactionData['systrade_no'] ,$mch_id , $this->getactionname(__METHOD__));
        $get_data['service'] = '0015'; // 此通道需要传动态类型
        $Lvyipay = new \Com\Pay\LvyiPay(array('mch_id' => $mch['mch_id'] , 'mch_key' => $mch['mch_key']));
        $res = $Lvyipay->getUrl($get_data);
        if($res != '') {
            // 订单创建成功
            $success_result = array(
                'error' => 0,
                'payurl' => $res['payUrl'],
                'code_img_url' => $res['payImg'],
                'ordernumber' => $get_data['ordernumber'],
                'msg' => '获取手Q窗口支付成功'
            );

            echo json_encode($success_result, JSON_UNESCAPED_UNICODE);
        }else{
            echo json_encode(array('error' => 5 , 'msg' => '渠道商导致的支付订单发起失败，未知错误'), JSON_UNESCAPED_UNICODE);
        }
    }


    public function Pay98($get_data){
        $pay_type = array('alipay_pay' => 'alipay' , 'WeixinScancode' => 'wechat' , 'qq_pay' => 'qq' , 'jd_pay' => 'jd');
        $get_data['acquirer_type'] = $pay_type[$get_data['banktype']];
        $oj = new \Com\Pay\Pay98($this->mch);
        $res = $oj->getUrl($get_data);
        if($res != '') {
            // 订单创建成功
            $this->PayResultReturn($get_data['systrade_no'] , $res['code_url'] , $get_data['ordernumber'] , $get_data['banktype']);
        }else{
            echo json_encode(array('error' => 5 , 'msg' => '渠道商导致的支付订单发起失败，未知错误'), JSON_UNESCAPED_UNICODE);
        }
    }


    // 轮训商户号
    private static function WeifutongLunxun($MaxPrice = 0.00 , $floatPrice = 0.00 , $Maxpen= 0 , $floatMaxpen = 0 , $PayName){
        // 原来已经满的笔数再增
        $floatPrice = $MaxPrice + $floatPrice;
        $floatMaxpen = $Maxpen + $floatMaxpen;
        $where = array(
            'pay_type' => $PayName,
            'CumulativePrice' => array('LT' , $MaxPrice),
            'penNum' => array('LT' , $Maxpen),
            'status' => 0
//            'pay_type' => s,
        );

        if($MaxPrice == 0) unset($where['CumulativePrice']);

        $Model = M("mch_data");

        /*
        $l = $Model = M("mch_data")->where(array('pay_type' => 'weifutongSM'))->select();

        foreach($l as $value){
            if( $value['penNum'] < $Maxpen ){
                // 如果指定设置的笔数已经超出实际交易笔数，则不使用指定交易的
                continue;
            }
        }
        */

        $Model->where($where)->find();

        $Count = $Model->count();
        $lastOrder = M("Transaction")->field('mch_id')->where(array('mch_type' => $PayName))->order('id desc')->limit(1)->getField('mch_id');
        $lastmch = $Model->where(array('mch_id' => $lastOrder , 'pay_type' => $PayName , 'status' => 0))->find(); // 最后一笔订单的商户号
        if(!empty($lastmch) && $lastmch['penNum'] < $Maxpen) {
            // 本来的商户号
            return $lastmch;
        }else{
//            dump($where);die;
//            $id = $lastmch['id'] + 1;
//            $where['id'] = $id;
            // 已经满了指定笔数，重新顺序分配
            $mch = $Model->field('id')->where($where)->select(); // 有可能满足条件的已经没有了
            if(count($mch) <= 0){
                // 最后一条轮训重新来
                /*
                @$Model->where(array('pay_type' => 'weifutongSM'))->setInc('penNum' , 3); // 指定笔数已经轮训完了，再给每个商户号的最大笔数增加3笔重新轮训
                return $Model->where($where)->order('id asc')->find(); // 重1到N重新轮训
                */
                // 使用浮动金额
                $floatwhere = array(
                    'CumulativePrice' => array('LT' , $floatPrice),
                    'penNum' => array('LT' , $floatMaxpen),
                    'pay_type' => $PayName,
                    'status' => 0
                );

                if($floatPrice == 0) unset($floatwhere['CumulativePrice']);
                $mchf = $mch =   $Model->field('id')->where($floatwhere)->select();

                if(count($mchf) <= 0) {
                    return false;
                }
            }
            $ids = array();
            foreach ($mch as $key => $val){
                $ids[] = (int)$val['id'];
            }
        }
//        $mch = $Model->where($where)->select();
//        $key = mt_rand(0,count($mch));
//        return $mch[$key];
        $idz = CreatePayController::NextNumberArray($lastmch['id'],$ids);
        if($idz == null) return false;
        return $Model->find($idz);
    }



//    private static function WeifutongLunxun($MaxPrice , $Maxpen){
//        $where = array(
//            'pay_type' => 'weifutongSM',
////            'CumulativePrice' => array('LT' , $MaxPrice),
//            // 'penNum' => array('LT' , $Maxpen),
//        );
//        $mch = M("mch_data")->where($where)->select();
//        $key = mt_rand(0,count($mch) - 1);
//        return $mch[$key];
//    }



    private static function NextNumberArray($Number, $NumberRangeArray){
        $w = 0;
        $c = -1;
        $abstand = 0;
        $l = count($NumberRangeArray);
        for($pos=0; $pos < $l; $pos++){
            $n = $NumberRangeArray[$pos];
            $abstand = ($n < $Number) ? $Number - $n : $n - $Number;
            if ($c == -1){
                $c = $abstand;
                continue;
            }
            else if ($abstand < $c){
                $c = $abstand;
                $w = $pos;
            }
        }
        return $NumberRangeArray[$w];
    }

}